<?php
$shortopts  = "";
$longopts = array(
  "host::",
  "port::"
);

$options = getopt($shortopts,$longopts);
!isset($options["host"]) && $options["host"] = "127.0.0.1";
!isset($options["prot"]) && $options["port"] = "8085"; 

$fp = stream_socket_client("tcp://".$options["host"].":".$options["port"],$errno,$errstr);
if(!$fp){
  echo "$errstr ($errno)",PHP_EOL;
}else{
  echo "tcp connect to ".$options["host"].":".$options["port"],PHP_EOL;


  $body = "this is a test!";
  $header = str_pad(strlen($body),10," ",STR_PAD_LEFT);
  $msg = $header.$body;
  $count = fwrite($fp, $msg);
  if($count === false){
    $error = error_get_last();
    echo "write err".$error["message"];
    return;
  }
  while(!feof($fp)){
    
   echo fgets($fp,10);
  }
  
  $header_r = fgets($fp,10);
  $size = intval(trim($header_r));
  if($size > 0){
    $body_r = fgets($fp,$size);
  }
  
  echo $header_r,PHP_EOL;
  echo $body_r,PHP_EOL;

  fclose($fp);
}